﻿/*
 * Created by SharpDevelop.
 * User: Lousabit
 * Date: 17/11/2011
 * Time: 10:04
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Business_Logic;
using Business_Entity;
using iTextSharp.text;
using iTextSharp.text.pdf;


namespace PetSoft.GUI.Ventas
{
	/// <summary>
	/// Description of GUIReporteVentas.
	/// </summary>
	public partial class GUIReporteVentas : Form
	{
		
		private List<BELineaReporteVenta> lineasReporte;
		
		public GUIReporteVentas()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void DesdeDTPValueChanged(object sender, EventArgs e)
		{
			Utils.dateMenorQue(desdeDTP, hastaDTP);
		}
		
		void HastaDTPValueChanged(object sender, EventArgs e)
		{
			Utils.dateMayorQue(hastaDTP, desdeDTP);
		}
		
		void GenerarBTNClick(object sender, EventArgs e)
		{
			
			 
			try{
				ventasMesCHART.Series[0].Points.Clear();
				
				lineasReporte = BLPedidoVenta.getReporte(desdeDTP.Value, hastaDTP.Value, tiendaCB.SelectedItem as BETienda);
				
				foreach(BELineaReporteVenta linea in lineasReporte){
					
					ventasMesCHART.Series[0].Points.AddY(linea.Monto);
					ventasMesCHART.Series[0].Points[
						ventasMesCHART.Series[0].Points.Count-1].AxisLabel = String.Format("{0:MMMM yyyy}", linea.Mes);
					
				}	
				
				mesesCB.Enabled = true;
				generarPDFBTN.Enabled = true;
				
				dibujarPieChart(0);
				
				llenarMesesCB();
								
			}catch(Exception ex){
				Utils.MessageError("Error al generar reporte.", ex);
			}
			
		}
		
		private void llenarMesesCB(){
			try{
				List<DateTime> meses = new List<DateTime>();
				
				foreach(BELineaReporteVenta linea in lineasReporte){
					meses.Add(linea.Mes);
				}
				
				mesesCB.DataSource = meses;
				mesesCB.FormatString = "MMMM yyyy";
			}catch(Exception ex){
				Utils.MessageError("Error al cargar meses", ex);
			}
			
		}
		
		void GUIReporteVentasLoad(object sender, EventArgs e)
		{
			//cargar combo de tiendas
			BLTienda blTienda = new BLTienda();
			
			tiendaCB.DataSource = blTienda.getAllTiendasFiorella();
			tiendaCB.DisplayMember = "Nombre";
		}
		
		private Byte[] getChart(System.Windows.Forms.DataVisualization.Charting.Chart chart){
			
			MemoryStream img = new MemoryStream();
			chart.SaveImage(img, System.Drawing.Imaging.ImageFormat.Png);
			
			return img.GetBuffer();
		}
		
		private void dibujarPieChart(int ind){
			
			BELineaReporteVenta linea = this.lineasReporte[ind];
			List<ProdLinea> pls = linea.Prods;
			List<ServLinea> sls = linea.Servs;

			//PIE PRODUCTOS			
			pieProdCHART.Series[0].Points.Clear();
			
			foreach(ProdLinea pl in pls){
				pieProdCHART.Series[0].Points.AddY(pl.monto);
				pieProdCHART.Series[0].Points[pieProdCHART.Series[0].Points.Count-1].Label = pl.producto+" S/."+pl.monto.ToString();
			}
			
			//PIE SERVICIOS
			pieServCHART.Series[0].Points.Clear();
			
			foreach(ServLinea sl in sls){
				pieServCHART.Series[0].Points.AddY(sl.monto);
				pieServCHART.Series[0].Points[pieServCHART.Series[0].Points.Count-1].Label = sl.servicio+" S/."+sl.monto.ToString();
			}
			
		}
		
		void GenerarPDFBTNClick(object sender, EventArgs e)
		{
			
			String path;
			
			try{
				Document doc = new Document(PageSize.A4.Rotate());
				path = "..\\ReporteVentas.pdf";
				
				PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
				doc.Open();	
				
				PdfPTable tab = new PdfPTable(2);
				tab.TotalWidth = 820f;
				float[] widths = new float[] { 410f, 410f};
				tab.SetWidths(widths);
				tab.LockedWidth = true;
				
				PdfPCell cell;
				iTextSharp.text.Image img;
				
				//AQUI VA EL LOGO DE PETSOFT!!!!!!!!!!!////////////////////////
				/////////////////////////////////////////////////////////////
				img = Utils.getEncabezadoReporte();
				cell = new PdfPCell(img, false);
				cell.Colspan = 2;
				cell.Border = 0;
				cell.HorizontalAlignment = 0;
				tab.AddCell(cell);
				//////////////////////////////////////////////////////
				/////////////////////////////////////////////////////////
				
				
				iTextSharp.text.Font fntTit = FontFactory.GetFont(FontFactory.HELVETICA, 16, BaseColor.WHITE);
				iTextSharp.text.Font fntTab = FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK);
							
				cell = new PdfPCell(new Phrase("REPORTE DE VENTAS",fntTit));
				cell.Colspan = 2;
				cell.Border = 0;
				cell.HorizontalAlignment = 1;
				cell.BackgroundColor = BaseColor.BLACK;
				tab.AddCell(cell);
				
				String mesIni = String.Format("{0:MMMM yyyy}", lineasReporte[0].Mes);
				String mesFin = String.Format("{0:MMMM yyyy}", lineasReporte[lineasReporte.Count-1].Mes);
				
				cell = new PdfPCell(new Phrase("Nivel de ventas de "+mesIni+" hasta "+mesFin,fntTab));
				cell.Colspan = 2;
				cell.BackgroundColor = BaseColor.LIGHT_GRAY;
				cell.Border = 0;
				tab.AddCell(cell);
							
				//IMAGENES CHART
					
				img = iTextSharp.text.Image.GetInstance(getChart(ventasMesCHART));
				//img.ScalePercent(75f);						
				cell = new PdfPCell(img, true);
				cell.Colspan = 2;
				cell.Border = 0;
				tab.AddCell(cell);
				
				//PIE CHART
				
				String strMes = String.Format("{0:MMMM yyyy}", mesesCB.SelectedValue);
				
				cell = new PdfPCell(new Phrase("Nivel de ventas por producto para "+strMes,fntTab));
				cell.Border = 0;
				cell.BackgroundColor = BaseColor.LIGHT_GRAY;
				tab.AddCell(cell);
	
				cell = new PdfPCell(new Phrase("Nivel de ventas por servicio para "+strMes,fntTab));
				cell.Border = 0;
				cell.BackgroundColor = BaseColor.LIGHT_GRAY;
				tab.AddCell(cell);
				
				
				img = iTextSharp.text.Image.GetInstance(getChart(pieProdCHART));
				//img.ScalePercent(75f);
				cell = new PdfPCell(img, true);
				cell.Border = 0;
				tab.AddCell(cell);
				
				img = iTextSharp.text.Image.GetInstance(getChart(pieServCHART));
				//img.ScalePercent(75f);
				cell = new PdfPCell(img, true);
				cell.Border = 0;
				tab.AddCell(cell);			
				
				doc.Add(tab);
				
				doc.Close();
			}catch(Exception ex){
				Utils.MessageError("Error al generar reporte.", ex);
				return;
			}	
			
			try{
				System.Diagnostics.Process.Start("AcroRd32.exe",path);
			}catch(Exception ex){
				Utils.MessageError("No se puede abrir el archivo generado.");
				return;
			}
			
			/*
			
			try{
				
				if (lineas == null || lineas.Count == 0){
					return;
				}
				int cont = 1;
				String path = "..\\..\\ReporteVentas.pdf";			
				
				Document doc = new Document(PageSize.A4.Rotate());
				doc.AddCreationDate();
				PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
				doc.Open();
				
				
				iTextSharp.text.Font fntTit = FontFactory.GetFont(FontFactory.COURIER_BOLD, 20, BaseColor.RED);
				iTextSharp.text.Font fntTab = FontFactory.GetFont(FontFactory.COURIER, 8, BaseColor.BLUE);
				iTextSharp.text.Font fntRes = FontFactory.GetFont(FontFactory.COURIER, 7);
				
				PdfPTable tab = new PdfPTable(2);
				tab.TotalWidth = 820f;
				float[] widths = new float[] { 410f, 410f};
				tab.SetWidths(widths);
				tab.LockedWidth = true;
				
				PdfPCell cell = new PdfPCell(new Phrase("REPORTE DE VENTAS",fntTit));
				cell.Colspan = 2;
				cell.HorizontalAlignment = 1;
				tab.AddCell(cell);
				
				PdfPCell cell2 = new PdfPCell(new Phrase("Mes",fntTab));
				cell2.HorizontalAlignment = Element.ALIGN_CENTER;
				cell2.VerticalAlignment = Element.ALIGN_CENTER;
				tab.AddCell(cell2);
				
				cell2 = new PdfPCell(new Phrase("Monto Vendido (S/.)",fntTab));
				cell2.HorizontalAlignment = Element.ALIGN_CENTER;
				cell2.VerticalAlignment = Element.ALIGN_CENTER;
				tab.AddCell(cell2);
				
				foreach (BELineaReporteVenta linea in lineas) {
					cell2 = new PdfPCell(new Phrase(String.Format("{0:MMMM}", linea.Mes)+" "+linea.Mes.Year.ToString(), fntRes));
					cell2.HorizontalAlignment = Element.ALIGN_CENTER;
					cell2.VerticalAlignment = Element.ALIGN_CENTER;
					tab.AddCell(cell2);
					
					cell2 = new PdfPCell(new Phrase(linea.Monto.ToString(), fntRes));
					cell2.HorizontalAlignment = Element.ALIGN_CENTER;
					cell2.VerticalAlignment = Element.ALIGN_CENTER;
					tab.AddCell(cell2);
				}
				
				doc.Add(tab);
				
				
				doc.Close();
								
				System.Diagnostics.Process.Start("AcroRd32.exe",path);
				this.Close();
			}
			catch (Exception ex)
			{
				MessageBox.Show("Exportación fallida\n" + ex, "Aviso");
			}
			*/
		}
		
		void MesesCBSelectedIndexChanged(object sender, EventArgs e)
		{
			try{
				for(int i=0; i<ventasMesCHART.Series[0].Points.Count;i++){
					ventasMesCHART.Series[0].Points[i].Color = Color.SkyBlue;
				}
				
				int ind = mesesCB.SelectedIndex;	
				ventasMesCHART.Series[0].Points[ind].Color = Color.CadetBlue;
				
				dibujarPieChart(ind);
			}catch(Exception ex){
				Utils.MessageError("Error al actualizar reporte para mes seleccionado.", ex);
			}
			
		}
	}
}
